package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService{

    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    @Transactional
    public void addAddressBook(AddressBook addressBook) {
        // 新增用户地址
            // 获取用户 user_id
        Long id = BaseContext.getCurrentId();
        addressBook.setUserId(id);
        addressBook.setIsDefault(0);// 设置地址为 非默认地址
        // 构建
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询用户默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefaultAddressBook() {
        // 构建查询条件
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1); // default  '默认 0 否 1是'
        addressBook.setUserId(userId);// 获取当前用户 user_id

        return addressBookMapper.list(addressBook).get(0);
    }

    /**
     * 查询用户所有地址
     *
     * @return
     */
    @Override
    public List<AddressBook> listAddressBook() {
        // 构建查询条件
        Long userId = BaseContext.getCurrentId(); // 当前用户的 user_id
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);
        List<AddressBook> addressBooks=addressBookMapper.list(addressBook);
        return addressBooks;
    }

    /**
     * 修改用户默认地址
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public void setDefaultAddressBook(Long id) {
        // 1.用户所有地址改为 非默认  ---is_default=0
        Long user_id= BaseContext.getCurrentId();
        addressBookMapper.updateAllDefault(user_id);
        // 2.修改默认地址，id
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setIsDefault(1); // 设置为默认地址
        addressBookMapper.update(addressBook);;
    }

    /**
     * 根据id查询用户地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressBookById(Long id) {
        AddressBook addressBook=addressBookMapper.selectById(id);
        return addressBook;
    }

    /**
     * 修改用户地址
     *
     * @param addressBook
     */
    @Override
    @Transactional
    public void setAddressBook(AddressBook addressBook) {
        Long userId= BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBookMapper.update(addressBook);
    }

    /**
     * 删除地址
     *
     * @param id
     */
    @Override
    public void del(Long id) {
        addressBookMapper.del(id);
    }
}
